package com.weixin.util;
/**
 * 验证码生成核心类
 * @author 唐鑫明
 *
 */

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RadialGradientPaint;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.Thread.State;
import java.util.Random;

import javax.imageio.ImageIO;

import org.apache.taglibs.standard.lang.jstl.test.StaticFunctionTests;

public class ValidateUtil {
	/**
	 * 验证码
	 * @param content
	 * @return
	 */
	 static Random random = new Random();
	public static BufferedImage getValiDateCode(String content) {
		//生成一张图片
		int width = 120;
		int height = 48;
		//画板
		BufferedImage buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		//画笔
		Graphics2D gs = buf.createGraphics();
		//设置颜色
		gs.setColor(getRandomColor(180,250));
		//绘制矩形
		gs.fillRect(0,0, width, height);
		//干扰线 起点（坐标x y）和终点（坐标 x y） 随机取四个数字，在图像上连起来 100 for
		for(int i = 0 ;i<100;i++) {
			//设置颜色
			gs.setColor(getRandomColor(50, 200));
			int x1 = random.nextInt(120);
			int y1 = random.nextInt(48);
			int x2 = x1 + random.nextInt(50);
			int y2 = y1 + random.nextInt(20);
			gs.drawLine(x1, y1, x2, y2);
		}
		float yawRate  = 0.01f;//噪点率
		int area = (int)(yawRate*width*height);
		for(int i = 0;i<area;i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			buf.setRGB(x, y, random.nextInt(255));
			
		}
		
		//字体 样式 加粗 大小
		Font font = new Font("宋体",Font.BOLD, 25);
		gs.setFont(font);
		//文字颜色
		gs.setColor(getRandomColor(10,150));
		//绘制文字
		gs.drawString(content, 10, 33);
//		try {
//			ImageIO.write(buf,"png", new File("D:/123456/lala.png"));
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
		return buf;
	}
	/**
	 * 随机色
	 * @param begin 开始值
	 * @param end 结束值
	 * @return
	 */
	public static Color getRandomColor(int begin,int end) {
		//创建一个随机对象
		Random random = new Random();
		int r = begin + random.nextInt(end-begin);
		int g = begin + random.nextInt(end-begin);
		int b = begin + random.nextInt(end-begin);
		return new Color(r, g, b);
	}
	
	public static void main(String[] args) {
		BufferedImage valiDateCode = getValiDateCode("龙飞凤舞");
		System.out.println(valiDateCode);
	}
}
